﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;
using System.IO;

namespace KPIS.GERP.GIMS.APP.APP_UI.Edit_Form
{
    public partial class ICM_Collect_Request : System.Web.UI.Page
    {
        IBLLPrePurchaseRequest bll = new PrePurchaseRequestBLL();
        IBLLPrePurchaseRequestItem bllPprItem = new PrePurchaseRequestItemBLL();
        int nCount = 0;
        double totalPrice = 0;
        IBLLPrePurchaseRequestCommittee bllPprCommittee = new PrePurchaseRequestCommitteeBLL();
        IBLLDocument bllPprFile = new DocumentBLL();
        PrePurchaseRequestRejectBLL bllPprReject = new PrePurchaseRequestRejectBLL();
        IBLLHrmEmployee bllEmployee = new HrmEmployeeBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadDetail();
                LoadGridItem();
                LoadGridCommittee();
                LoadGridFile();
                LoadGrid_Reject();
            }
        }

        public void LoadDetail()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            PrePurchaseRequestInfo info = bll.GetPrePurchaseRequest(seq);
            string day = "";
            string month = "";
            string year = "";

            lblYearType.Text = info.InfoYearType.Name;
            lblYear.Text = info.Year.ToString();
            lblJobSite.Text = info.InfoJobSite.Name;

            string[] all_date = info.DateRequested.ToString().Split('/');
            if (all_date[0].Length > 0)
            {
                if (all_date[0].Length < 2)
                {
                    day = "0" + all_date[0];
                }
                else
                {
                    day = all_date[0];
                }
                if (all_date[1].Length < 2)
                {
                    month = "0" + all_date[1];
                }
                else
                {
                    month = all_date[1];
                }

                year = all_date[2];
                lblDate.Text = day + "/" + month + "/" + year.Substring(0,4);
            }

            lblPurchaseType.Text = info.InfoPurchaseType.Name;
            lblName.Text = info.Name;
            lblReason.Text = info.Reason;
            lblPprFor.Text = info.InfoPprFor.Name;

            string DateReq = "";
            if (info.DateRequired != null)
            {
                all_date = info.DateRequired.ToString().Split('/');
                if (all_date[0].Length > 0)
                {
                    if (all_date[0].Length < 2)
                    {
                        day = "0" + all_date[0];
                    }
                    else
                    {
                        day = all_date[0];
                    }
                    if (all_date[1].Length < 2)
                    {
                        month = "0" + all_date[1];
                    }
                    else
                    {
                        month = all_date[1];
                    }

                    year = all_date[2];
                    DateReq = day + "/" + month + "/" + year.Substring(0, 4);
                }
                lblDuration.Text = "ภายในวันที่ " + DateReq;
            }
            if (info.DurationRequired != null)
            {
                lblDuration.Text = "ภายใน " + info.DurationRequired + info.InfoDurationType.Name + " นับจาก" + info.InfoDurationCount.Name;
            }
        }

        protected void LoadGridItem()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            IList<PrePurchaseRequestItemInfo> infoList = bllPprItem.GetPrePurchaseRequestItemWithParent(seq);
            Grid_Item.DataSource = infoList;
            GridGroupByExpression geSource = new GridGroupByExpression(Grid_Item.Columns[0]);
            GridGroupByExpression geExpense = new GridGroupByExpression(Grid_Item.Columns[1]);
            GridGroupByExpression geRule = new GridGroupByExpression(Grid_Item.Columns[2]);
            GridGroupByExpression geProOper = new GridGroupByExpression(Grid_Item.Columns[3]);
            GridGroupByExpression geProject = new GridGroupByExpression(Grid_Item.Columns[4]);

            if (infoList.Count > 0)
            {
                Grid_Item.MasterTableView.GroupByExpressions.Add(geRule);
                if (infoList[0].InfoOperationExpense.InfoOperation.Seq != null)
                {
                    Grid_Item.MasterTableView.GroupByExpressions.Add(geProOper);
                }
                if (infoList[0].InfoProjectExpense.InfoProject.Seq != null)
                {
                    Grid_Item.MasterTableView.GroupByExpressions.Add(geProject);
                }
                Grid_Item.MasterTableView.GroupByExpressions.Add(geSource);
                Grid_Item.MasterTableView.GroupByExpressions.Add(geExpense);
            }

            Grid_Item.DataBind();
        }

        protected void LoadGridCommittee()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            Grid_Committee.DataSource = bllPprCommittee.GetPrePurchaseRequestCommitteeWithParent(seq);
            GridGroupByExpression geFunction = new GridGroupByExpression(Grid_Committee.Columns[0]);
            GridGroupByExpression geRefNo = new GridGroupByExpression(Grid_Committee.Columns[1]);
            Grid_Committee.MasterTableView.GroupByExpressions.Add(geFunction);
            Grid_Committee.MasterTableView.GroupByExpressions.Add(geRefNo);
            Grid_Committee.DataBind();
        }

        protected void LoadGridFile()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            Grid_File.DataSource = bllPprFile.GetDocument(seq, "ICM_PRE_PURCHASE_REQUEST_FILE", "ICM_PPR_SEQ", "ICM_PPR_FILE_SEQ");
            Grid_File.DataBind();
        }

        protected void LoadGrid_Reject()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            IList<PrePurchaseRequestRejectInfo> InfoPprReject = bllPprReject.GetHistoryReturned(seq);
            Grid_Reject.DataSource = InfoPprReject;
            Grid_Reject.DataBind();
        }

        protected void Grid_Item_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridItem();
        }

        protected void Grid_Item_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (nCount == 0)
            {
                totalPrice = 0;
            }
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                nCount++;
                double qty = 0;
                double price = 0;
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Control target = e.Item.FindControl("lkName");

                if (dataBoundItem["Qty"].Text.Length > 0)
                {
                    qty = double.Parse(dataBoundItem["Qty"].Text);
                }
                if (((Label)(dataBoundItem["Price"].FindControl("lblPrice"))).Text.Length > 0)
                {
                    price = double.Parse(((Label)(dataBoundItem["Price"].FindControl("lblPrice"))).Text);
                }

                GridDataItem gridDataItem = (GridDataItem)e.Item;
                Image image = (Image)gridDataItem["Image"].FindControl("Image1");
                if (dataBoundItem["InfoPrItem.Seq"].Text.Replace("&nbsp;", "") != "")
                {
                    image.ImageUrl = "../Image/Grid/Cancel.gif"; 
                }
                else
                { 
                    image.ImageUrl = "../Image/Grid/Update.gif";
                }

                totalPrice += (qty * price);

                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(TipItemDetail, null))
                    {
                        TipItemDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["InfoItem.Seq"].Text, true);
                    }
                }
            }
            else if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["Descr"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>วงเงินจัดหาทั้งหมด :</span> "));
                ((Label)footer["Price"].FindControl("lblTotalPrice")).Text = totalPrice.ToString("###,###,##0.00");
                nCount = 0;
            }
        }

        protected void OnAjaxUpdateItemDetail(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTipItemDetail(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTipItemDetail(string elementID, UpdatePanel panel)
        {
            string[] all_value = elementID.Split(new string[] { ":" }, StringSplitOptions.None);
            Session["Resource_Item_Id"] = all_value[1];
            Control ctrl = Page.LoadControl("../UserControl/TIP_Item_Detail.ascx");
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void Grid_Committee_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridCommittee();
        }

        protected void Grid_File_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridFile();
        }

        protected void Grid_Reject_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGrid_Reject();
        }
        
        protected void cbOperationName_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<HrmEmployeeInfo> infoList = bllEmployee.GetHrmEmployee(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                RadComboBox cbAppEmp = (RadComboBox)sender;
                cbAppEmp.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdJobSite = new TableCell();
                Label lblJobSite = new Label();
                lblJobSite.Text = infoList[i].InfoJobSite.Name;
                tdJobSite.Width = Unit.Pixel(200);
                tdJobSite.Controls.Add(lblJobSite);
                tr.Cells.Add(tdJobSite);
                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(150);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                TableCell tdPosition = new TableCell();
                Label lblPosition = new Label();
                lblPosition.Text = infoList[i].InfoPosition.Name;
                tdPosition.Width = Unit.Pixel(150);
                tdPosition.Controls.Add(lblPosition);
                tr.Cells.Add(tdPosition);
                TableCell tdClass = new TableCell();
                Label lblClass = new Label();
                lblClass.Text = infoList[i].InfoClass.Name;
                tdClass.Width = Unit.Pixel(190);
                tdClass.Controls.Add(lblClass);
                tr.Cells.Add(tdClass);
                ((Table)cbAppEmp.Items[j].FindControl("tableOperationName")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        private string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }

        protected void btnSendTo_Click(object sender, EventArgs e)
        {
            try
            {
                int seq = Convert.ToInt32(Request.QueryString["Seq"]);
                DateTime PrDate = Convert.ToDateTime(txtDate.Text.Substring(0, 2) + "/" + txtDate.Text.Substring(2, 2) + "/" + txtDate.Text.Substring(4, 4));
                int EmpSeq = Convert.ToInt32(cbOperationName.SelectedValue.ToString());
                bll.SendToPurchaseRequest(seq, PrDate, EmpSeq);
                RadManager1.ResponseScripts.Add(@"CloseWindow();");
                RadManager1.Alert("ส่งรายการไปยังผู้ดำเนินการเรียบร้อยแล้ว");
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
            }
        }

        protected void btnSendBack_Click(object sender, EventArgs e)
        {
            try
            {
                bllPprReject.Insert(Convert.ToInt32(Request.QueryString["Seq"]), DateTime.Now, txtReject.Text, 1);
                RadManager1.ResponseScripts.Add(@"CloseWindow();");
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
            }
        }
    }
}
